﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using Newtonsoft.Json;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using HtmlAgilityPack;


namespace ITU.Yemekhane.App7
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private Action<List<string>> MorningCallback;
        private Action<List<string>> LaunchCallback;
        private string requestedDate;

        public static string MenuUrl = "http://www.sks.itu.edu.tr/index.php?option=com_jevents";
        public static string BaseUrl = "http://www.sks.itu.edu.tr";

        public MainViewModel()
        {
            this.ItemsLeft = new ObservableCollection<ItemViewModel>();
            this.ItemsRight = new ObservableCollection<ItemViewModel>();
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ItemViewModel> ItemsLeft { get; private set; }
        public ObservableCollection<ItemViewModel> ItemsRight { get; private set; }

        public bool IsDataLeftLoaded
        {
            get;
            private set;
        }

        public bool IsDataRightLoaded
        {
            get;
            private set;
        }

        public void LoadLeftData(List<string> FoodData)
        {
            foreach (string item in FoodData)
            {
                this.ItemsLeft.Add(new ItemViewModel() { LineOne = item, LineTwo = "", LineThree = "" });
            }
            this.IsDataLeftLoaded = true;
        }

        public void LoadRightData(List<string> FoodData)
        {
            foreach (string item in FoodData)
            {
                this.ItemsRight.Add(new ItemViewModel() { LineOne = item, LineTwo = "", LineThree = "" });
            }
            this.IsDataRightLoaded = true;
        }

        public void LoadData()
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                getMenu(DateTime.Today, (result) =>
                {
                    LoadLeftData(result);
                }, (lunchResult) =>
                {
                    LoadRightData(lunchResult);
                });
            }
            else
            {
                MessageBoxResult mb = MessageBox.Show("Lütfen bağlantı ayarlarını kontrol edip tekrar deneyiniz.", "Bilgi", MessageBoxButton.OKCancel);
            }
        }

        public void getMenu(DateTime Datetime, Action<List<string>> _mcallback, Action<List<string>> _lcallback)
        {
            this.MorningCallback = _mcallback;
            this.LaunchCallback = _lcallback;

            requestedDate = Datetime.ToString("dd.MM.yyyy");

            WebClient client = new WebClient();
            client.DownloadStringAsync(new Uri(MenuUrl));
            client.DownloadStringCompleted += client_DownloadStringCompleted;
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string htmlResult = e.Result;
            Regex aElementsWithClass = new Regex(@"<a class\b[^>]*>(.*?)</a>");
            Regex hrefAttribute = new Regex("href=\\\"(.*?)\\\"");
            MatchCollection regexCollection = aElementsWithClass.Matches(htmlResult);
            Dictionary<bool, string> urlDictionary = new Dictionary<bool, string>();
            foreach (Match item in regexCollection)
            {
                if (item.Value.Contains(requestedDate))
                {
                    bool _morning = true;
                    if (item.Value.Contains("9:01"))
                    {
                        _morning = true;
                    }
                    else
                    {
                        _morning = false;
                    }
                    Match attribute = hrefAttribute.Match(item.Value);
                    string hrefResult = attribute.Value;
                    hrefResult = hrefResult.Replace("href=\"", "").Replace("\"", "");
                    if (!urlDictionary.ContainsKey(_morning))
                    {
                        urlDictionary.Add(_morning, hrefResult);
                    }
                }
            }
            if (urlDictionary.Count != 2)
            {
                DateTime rDate = DateTime.Parse(requestedDate);

                LoadLeftData(new List<string>() { "Haftasonu ve özel günlerde hizmet vermemektedir" });
                LoadRightData(new List<string>() { "Haftasonu ve özel günlerde hizmet vermemektedir" });
            }
            else
            {

                string morningURL = urlDictionary[true];
                string launchURL = urlDictionary[false];

                WebClient morningClient = new WebClient();
                morningClient.DownloadStringAsync(new Uri(string.Format("{0}{1}", BaseUrl, morningURL)));
                morningClient.DownloadStringCompleted += morningClient_DownloadStringCompleted;

                WebClient launchClient = new WebClient();
                launchClient.DownloadStringAsync(new Uri(string.Format("{0}{1}", BaseUrl, launchURL)));
                launchClient.DownloadStringCompleted += launchClient_DownloadStringCompleted;
            }
        }

        private List<string> getMenuFromPage(string PageHTML)
        {
            List<string> result = new List<string>();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(PageHTML);
            HtmlNode ulNode = doc.DocumentNode.SelectSingleNode("//table[@id='jevents_body']//ul");
            if (ulNode != null)
            {
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//table[@id='jevents_body']//ul//li"))
                {
                    result.Add(link.InnerText);
                }
            }
            else
            {
                result = new List<string>() { "Haftasonu ve özel günlerde hizmet vermemektedir" };
            }
            return result;
        }

        private void launchClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            LaunchCallback(getMenuFromPage(e.Result));
        }

        private void morningClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            MorningCallback(getMenuFromPage(e.Result));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}